package com.xdhl.fu.fi.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xdhl.fu.common.core.utils.DateUtils;
import com.xdhl.fu.common.core.utils.StringUtils;
import com.xdhl.fu.common.core.web.controller.BaseController;
import com.xdhl.fu.common.core.web.domain.AjaxResult;
import com.xdhl.fu.common.redis.service.RedisService;
import com.xdhl.fu.fi.repository.MGFlightScheduleRepository;
import com.xdhl.fu.fi.service.IFlightStockService;
import com.xdhl.fu.fi.utils.CacheKeyPrefix;
import com.xdhl.fu.flight.info.api.domain.FlightStock;
import com.xdhl.fu.flight.info.api.domain.vo.FlightScheduleVO;
import com.xdhl.fu.flight.info.api.mongodb.domain.MGFlightSchedule;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Optional;

/**
 * 航班搜索控制器
 *
 * @author 朱力维
 * @time 2022/6/15 14:37
 */
@RestController
@RequestMapping("/search")
public class FlightSearchController extends BaseController {

    @Resource
    private MGFlightScheduleRepository mgFlightScheduleRepository;

    @Resource
    private IFlightStockService flightStockService;

    @Resource
    private RedisService redisService;

    @Resource
    private CacheKeyPrefix cacheKeyPrefix;

    /**
     * 查询最新航班信息列表
     */
    @GetMapping("/list/new")
    public AjaxResult listNew() throws Exception {
        return AjaxResult.success(mgFlightScheduleRepository.findAll(PageRequest.of(0, 10)).getContent());
    }

    /**
     * 查询航班信息列表
     */
    @GetMapping("/list")
    public AjaxResult list(FlightScheduleVO flightScheduleVO) throws Exception {

        int check = 0;

        if (StringUtils.isNotBlank(flightScheduleVO.getFlightNumber())) {
            check += 2;
        }

        if (StringUtils.isNotBlank(flightScheduleVO.getFrom())) {
            check += 1;
        }

        if (StringUtils.isNotBlank(flightScheduleVO.getTo())) {
            check += 1;
        }

        // 查询校验
        if (check < 2) {
            return AjaxResult.error("请选择正确的出发地或航班号后进行查询。");
        }

        MGFlightSchedule mgFlightSchedule = new MGFlightSchedule();
        if (StringUtils.isNotBlank(flightScheduleVO.getFlightNumber())) {
            mgFlightSchedule.setFlightNumber(flightScheduleVO.getFlightNumber());
        }
        mgFlightSchedule.setStartStation(flightScheduleVO.getFrom());
        mgFlightSchedule.setEndStation(flightScheduleVO.getTo());
        mgFlightSchedule.setStartDate(flightScheduleVO.getWhen().format(DateTimeFormatter.ofPattern(DateUtils.YYYY_MM_DD)));
        Example<MGFlightSchedule> example = Example.of(mgFlightSchedule, ExampleMatcher.matchingAll());
        List<MGFlightSchedule> page = mgFlightScheduleRepository.findAll(example);
        return AjaxResult.success(page);
    }

    /**
     * 获取航班信息详细信息
     */
    @GetMapping(value = "/{dataId}")
    public AjaxResult getInfo(@PathVariable("dataId") String dataId) {
        Optional<MGFlightSchedule> mgFlightSchedule = mgFlightScheduleRepository.findById(dataId);

        String seatCachePrefix = cacheKeyPrefix.getSeatCachePrefix(dataId);

        if (!redisService.hasKey(seatCachePrefix + "A") && !redisService.hasKey(seatCachePrefix + "B") && !redisService.hasKey(seatCachePrefix + "C")) {
            LambdaQueryWrapper<FlightStock> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(FlightStock::getFlightScheduleDataId, dataId);
            FlightStock flightStock = flightStockService.getOne(wrapper);

            redisService.incr(seatCachePrefix + "A", flightStock.getHeadSeatRemainderCount());
            redisService.incr(seatCachePrefix + "B", flightStock.getBusinessSeatRemainderCount());
            redisService.incr(seatCachePrefix + "C", flightStock.getEconomySeatRemainderCount());
        }

        return AjaxResult.success(mgFlightSchedule.orElse(new MGFlightSchedule()));
    }

}
